package jus.aor.mobilagent.hostel;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import jus.aor.mobilagent.kernel._Service;


public class Chaine implements _Service<List<Hotel>> {

	private Document doc = null;
	//private int id;
	private List<Hotel> list_hotel;
	
	DocumentBuilder docBuilder;
	
	// Standard of reading a XML file
	//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

	//public Chaine(String adresse,int id) throws RemoteException {
	public Chaine(Object...params) throws RemoteException {
			//this.id = id;
		try {
			docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			//doc = docBuilder.parse(adresse);
			doc = docBuilder.parse((String)params[0]);
			list_hotel = new ArrayList<Hotel>();
			
			String name, loc;
			NodeList list = doc.getElementsByTagName("Hotel");
			NamedNodeMap attrs;
			/* acquisition de toutes les entrées de la base d'hôtels */
			for(int i =0; i<list.getLength();i++) {
				attrs = list.item(i).getAttributes();
				name=attrs.getNamedItem("name").getNodeValue();
				loc=attrs.getNamedItem("localisation").getNodeValue();
				list_hotel.add(new Hotel(name,loc));		
			}
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(" \n Numero de chaine d'Hotel non repertorié, Bye");
			System.exit(1);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	//	System.out.println("[Chaine] chaine "+ this.id + " create");
	}

	@Override
	public List<Hotel> call(Object... params) throws IllegalArgumentException {

		List<Hotel> listHotelTmp = new ArrayList<Hotel>();
		
		for(Hotel h : list_hotel)
		{
			//System.out.println(h.getName() + " "+h.getLocalisation() );
			if (h.getLocalisation().equals((String)params[0]))
				listHotelTmp.add(h);
		}
		 return listHotelTmp;
	}
	
	

}
